package demo02.actor;

import akka.actor.AbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import demo02.model.Agent;
import demo02.model.Corp;
import demo02.model.CorpTemp;
import demo02.model.User;
import demo02.util.ConnectDb;
import demo02.util.StringUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.commons.lang.StringUtils;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

/**
 * Created by 抽离 on 2017/6/22 0022.
 */
public class AgentMerger extends AbstractActor {
    private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);

    private Connection connection = ConnectDb.Connect();
    private QueryRunner queryRunner = new QueryRunner();

    private String selectUserSql = "select * from user where tel=? AND city_id=?";

    private String updateAgentSql = "update set agent corp_id = ?, user_id = ? where agent_id=?";

    private String selectCorpSql = "select * from corp where corp_name = ? AND city_id = ?";

    private String addCorpSql = "insert corp values(null, ?, ?, ?)";

    private String addCorpTempSql = "insert corp_temp values(null, ?, ?, ?, ?)";

    private String selectCorpTempSql = "select * from corp_temp where corp_name = ? AND city_id = ?";

    @Override
    public Receive createReceive() {
        return
                receiveBuilder()
                        .match(Agent.class, this::onReceiveAgent)
                        .build();
    }

    private void onReceiveAgent(Agent agent) {
        try {
            User user = (User) queryRunner.query(connection, selectUserSql,  new BeanHandler(User.class),agent.getTel(), agent.getCityId());
            if(user != null){//用户存在的话，只要更新agent
                agent.setCorpId(user.getCorpId());
                agent.setUserId(user.getUserId());
                queryRunner.update(connection, updateAgentSql, new Object[]{
                        agent.getCorpId(),
                        agent.getCityId(),
                        agent.getAgentId()
                });
            }
            else{//用户不存在，先处理好公司
                if(StringUtils.isEmpty(agent.getCorp())){//没有公司就所属于其它
                    Corp corp = queryRunner.query(connection, selectCorpSql, new BeanHandler<Corp>(Corp.class), "其它", agent.getCityId());
                    if(corp == null){//没有其它的话，创建其它，并且更新agent
                        queryRunner.update(connection, addCorpSql, "其它", agent.getCityId(), new Date());
                        BigInteger id =  queryRunner.query(connection, "SELECT LAST_INSERT_ID()", new ScalarHandler<BigInteger>(1));
                        agent.setCorpId(id.intValue());
                    }
                    agent.setCorpId(corp.getCorpId());
                }
                else{//公司存在，处理公司名
                    CorpTemp corpTemp = queryRunner.query(connection, selectCorpTempSql, new BeanHandler<CorpTemp>(CorpTemp.class), agent.getCorp(), agent.getCityId());
                    if(corpTemp != null){//公司临时表里找到了
                        agent.setCorpId(corpTemp.getCorpId());
                    }
                    else{//临时表没有，去公司表找
                        String corpName = StringUtil.processCorpNameNil(agent.getCorp());
                        Corp corp = queryRunner.query(connection, selectCorpSql, new BeanHandler<Corp>(Corp.class), corpName, agent.getCityId());
                        if(corp == null){
                            queryRunner.update(connection, addCorpSql, corpName, agent.getCityId(), new Date());
                            BigInteger id =  queryRunner.query(connection, "SELECT LAST_INSERT_ID()", new ScalarHandler<BigInteger>(1));
                            CorpTemp ct = new CorpTemp();
                            ct.setCorpId(id.intValue());
                            ct.setCorpName(agent.getCorp());
                            ct.setCityId(agent.getCityId());
                            ct.setStaffCount(1);
                            queryRunner.update(connection, addCorpTempSql, ct);
                            agent.setCorpId(id.intValue());
                        }
                    }
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }
}
